package com.wxlsoft.utils;

import java.security.AccessController;
import java.util.Objects;

import javax.swing.JTextArea;

public class LogUtils {

	public static final String LINE = AccessController.doPrivileged(new sun.security.action.GetPropertyAction("line.separator"));
	
	public static JTextArea log = new JTextArea(10,10);

	public static void info(String format) {
		log.append(format);
		log.append(LINE);
	}

	public static void error(String format, Exception e) {
		log.append(format);
		log.append(buildConsoleStack(e));
	}

    /**
     * 构造堆栈信息
     *
     * @param cause
     * @return
     */
    public static String buildConsoleStack(Throwable e) {
        StringBuilder build = new StringBuilder(512);
        StackTraceElement[] traces = e.getStackTrace();
        build.append("[error] > ").append(e.getClass().getName()).append(": ").append(e.getMessage()).append("\n");
        for (int i = 0, len = traces.length; i < len; i++) {
            if (i == 10) {
                break;
            }
            StackTraceElement trace = traces[i];
            if (Objects.nonNull(trace)) {
                build.append("		    [error] > ");
                build.append(trace.getClassName()).append(".").append(trace.getMethodName());
                build.append("at").append("(").append(trace.getFileName()).append(":").append(trace.getLineNumber()).append(")").append("\n");
            }
        }
        return build.deleteCharAt(build.length() - 1).toString();
    }

	public static void clean() {
		log.setText("");
	}
    
}
